package com.example.demo.controller

import com.example.demo.entity.User
import com.example.demo.service.UserService
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.*
import org.springframework.web.servlet.ModelAndView
import java.util.*

@Controller
class UserController(var userService: UserService) {
    @GetMapping("User/List")
    fun List(): ModelAndView {
        var mav = ModelAndView("user/list")
        var users = userService.GetUsers()
        mav.addObject("list", users)
        return mav
    }

    @GetMapping("User/Detail/{id}")
    fun Detail(@PathVariable id: Int): ModelAndView {
        var mav = ModelAndView("user/detail")
        var user = userService.GetById(id)
        mav.addObject("user", user)
        return mav
    }

    @GetMapping("User/Create")
    fun Create(): ModelAndView {
        return ModelAndView("user/create")
    }

    @PostMapping("User/Create")
    fun Create(user: User): ModelAndView {
        var mav = ModelAndView()
        try {
            mav.viewName = "redirect:List"
            userService.SaveUser(User(UserName = user.UserName, CreatedDate = Date()))
        } catch (e: Exception) {
            mav.viewName = "user/create"
        }
        mav.addObject("user", user)
        return mav
    }
}